package common

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

type HttpHelper struct {
	Data   *url.Values
	Header http.Header
	//ApiUrl    *url.URL
	ApiUrl string
	Method string
	Body   *[]byte
}

var (
	client *http.Client
)

func init() {
	client = &http.Client{
		Transport: &http.Transport{
			IdleConnTimeout:     time.Duration(2) * time.Hour,
			MaxIdleConnsPerHost: 10,
		},
		Timeout: time.Minute,
	}
}

func (h *HttpHelper) Do() (text []byte, err error) {
	var body io.Reader
	if h.Data != nil {
		body = bytes.NewBufferString(h.Data.Encode())
	} else if h.Body != nil {
		body = bytes.NewReader(*h.Body)
	}

	req, err := http.NewRequest(h.Method, h.ApiUrl, body)
	if err != nil {
		return nil, err
	}
	req.Header = h.Header
	rsp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer rsp.Body.Close()
	if rsp.StatusCode != 200 && rsp.StatusCode != 204 {
		return nil, fmt.Errorf("rsp code not 200: %+v, head:%+v", rsp, h)
	}
	text, err = ioutil.ReadAll(rsp.Body)
	if err != nil {
		return nil, err
	}
	return
}
